package com.rockcent.mall.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.mall.Routes;
import com.rockcent.mall.helper.UserHelper;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.ProductStatus;
import com.rockcent.mall.lib.dto.ProductDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.MerchantProductSrv;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * M端产品管理
 * Created by Marco on 16-11-14.
 */
@RestController
public class MallProductController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MallProductController.class);

    @Autowired
    MallProductRepository mallProductRepository;

    @Autowired
    private MerchantProductCategoriesRepository merchantProductCategoriesRepository;
//
//    @Autowired
//    private ProductHelper productHelper;
    @Autowired
    private MerchantProductSrv merchantProductSrvImpl;

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MerchantProductDetailRepository merchantProductDetailRepository;

    @Autowired
    MallProductReasonRepository mallProductReasonRepository;

    @Autowired
    private ProductQuantityRepository productQuantityRepository;

    @Autowired
    private UserHelper userHelper;

    /**
     * @api {get} /mall/product/query 产品管理 产品 分页
     * @apiGroup M端 product
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} name 产品名称
     * @apiParam {Long} id 产品编号
     * @apiParam {String} type 产品类型 默认为空
     * @apiParam {String} status 产品状态 默认为空
     * @apiParam {String} merchantName 商家
     * @apiParam {String} beginDate 上架开始时间
     * @apiParam {String} endDate 上架结束时间
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize
     *
     * @apiSuccess {Long} id 产品ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {String} type 产品类型
     * @apiSuccess {String} name 产品名称
     * @apiSuccess {String} categoryName 类目名称
     * @apiSuccess {BigDecimal} basePrice 原价
     * @apiSuccess {BigDecimal} sellPrice 出售价
     * @apiSuccess {Long} quantity 库存量
     * @apiSuccess {String} barcode 产品编号
     * @apiSuccess {BigDecimal} carriage 运费
     * @apiSuccess {boolean} refundable 是否支持过期退
     * @apiSuccess {boolean} sellnow 是否立即开售
     * @apiSuccess {Date} dateSelling 开售时间
     * @apiSuccess {Long} limitCount 限购数
     * @apiSuccess {String} logoUrl LOGO图
     * @apiSuccess {String} note 卖点介绍
     * @apiSuccess {String=SELLING("在售"), SOLDOUT("已下架"), EXPIRED("已过期"), DELETED("已删除"), WAIT_APPLY("待申请"), WAIT_AUDIT("待审核"), AUDIT_PASS("审核通过"), AUDIT_FAIL("审核不通过")} status 产品状态
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {String} serveRate 服务费比率
     * @apiSuccess {String=SHOP_PICKUP("到店自取"), SHIPPING("物流"), SHOP_PICKUP_AND_SHIPPING("物流及到店自取")} shippingType 支持的物流类型
     * @apiSuccess {String} viewCount 浏览数
     * @apiSuccess {String} buyNum 售出数
     * @apiSuccess {String} settleNum 核销数
     * @apiSuccess {String} identifier 产品唯一的识别码
     * @apiSuccess {String} marketIdentifier 分销产品唯一的识别码
     * @apiSuccess {String} marketProductType 分销市场属性
     * @apiSuccess {String} extSourceId 供应商ID
     * @apiSuccess {String} marketPlatformType 平台属性
     * @apiSuccess {String} merchantName 商家名称
     * @apiSuccess {String} resellFee 分销佣金
     * @apiSuccess {String} shareFee 分享返利
     * @apiSuccess {Date} dateEnabled 有效期开始时间
     * @apiSuccess {Date} dateDisabled 有效期结束时间
     * @apiSuccess {String} cAccessUrl C端访问链接
     * @apiSuccess {String} promoteUrl 推广二维码图片链接
     * @apiSuccess {String} auditRemark 审批备注
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     * "data": [
     *      {
     *          "id": 71,
     *          "dateCreated": "2016-06-01 14:13:43",
     *          "lastUpdated": "2016-07-22 10:49:28",
     *          "type": "GOODS",
     *          "name": "宇宙",
     *          "basePrice": 110,
     *          "sellPrice": 100,
     *          "quantity": 998,
     *          "carriage": 0,
     *          "refundable": false,
     *          "barcode": 2342342,
     *          "sellnow": true,
     *          "dateSelling": "2016-06-01 14:13:43",
     *          "limitCount": 0,
     *          "logoUrl": "/20160601/201606011413084VOvLKgN.jpg",
     *          "note": "全宇宙最漂亮的",
     *          "status": "SELLING",
     *          "mallId": 1,
     *          "merchantId": 1,
     *          "serveRate": "2.4",
     *          "shippingType": "SHIPPING",
     *          "resellFee": 5,
     *          "shareFee": 2,
     *          "viewCount": "35",
     *          "saleCount": "2"
     *          "verifyCount": "2"
     *          "identifier": "dfsdwrwers334rnwfu"
     *          "marketIdentifier": "36ca173cd8cc74f8233898909f7a242c",
     *          "marketProductType": "TARGET",
     *          "marketPlatformType": "OUT_PLATFORM",
     *          "extSourceId": "29",
     *          "dateEnabled": "2016-06-01 14:13:43",
     *          "dateDisabled": "2016-06-01 14:13:43",
     *          "cAccessUrl":"http://quancome.c.rockcent.com/xxxx",
     *          "promoteUrl":"http://uploads.rockcent.com/dev/product/promote/xxxx.jpg",
     *          "auditRemark":"萨里的复活节啊接受的"
     *       }
     *    ],
     *    "totalCount": 24,
     *    "totalPage": 24,
     *    "pageNo": 0,
     *    "pageSize": 1
     *   }
     * }
     */
    @RequestMapping(value = Routes.MALL_PRODUCT_QUERY, method = RequestMethod.GET)
    public JsonResult query(HttpServletRequest request, ProductDto productDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if(productDto.getId()!=null && productDto.getId().longValue()<=0) {
                jsonResult.remind("产品编号必为大于0数字",log);
                return;
            }
            if(StringUtils.isNotBlank(productDto.getBeginDate()) && !isDate(productDto.getBeginDate())) {
                jsonResult.remind("上架开始时间格式不正确",log);
                return;
            }
            if(StringUtils.isNotBlank(productDto.getBeginDate()) && !isDate(productDto.getEndDate())) {
                jsonResult.remind("上架结束时间格式不正确",log);
                return;
            }
            PageResult<ProductDto> pageResult =mallProductRepository.findMerchantProductQuery(userInfoDto.mall.getId(),productDto.getName(),productDto.getId(),productDto.getType(),productDto.getStatus(),productDto.getMerchantName(),productDto.getBeginDate(),productDto.getEndDate(),this.getPage(productDto.getPageNo(), productDto.getPageSize()));
            if(pageResult==null) {
                jsonResult.remind("产品查询没有找到合适记录",log);
                return;
            }
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get}/mall/product/info 产品管理 产品 详情
     * @apiGroup M端 product
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id <code>必须参数</code> 产品ID
     *
     * @apiSuccess {Long} id 产品ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {String} type 产品类型
     * @apiSuccess {String} name 产品名称
     * @apiSuccess {BigDecimal} basePrice 原价
     * @apiSuccess {BigDecimal} sellPrice 出售价
     * @apiSuccess {Long} quantity 库存量
     * @apiSuccess {String} barcode 产品编码
     * @apiSuccess {BigDecimal} carriage 运费
     * @apiSuccess {boolean} refundable 是否支持过期退
     * @apiSuccess {boolean} sellnow 是否立即开售
     * @apiSuccess {Date} dateSelling 开售时间
     * @apiSuccess {Long} limitCount 限购数
     * @apiSuccess {String} logoUrl LOGO图
     * @apiSuccess {String} note 卖点介绍
     * @apiSuccess {String=SELLING("在售"), SOLDOUT("已下架"), EXPIRED("已过期"), DELETED("已删除"), WAIT_APPLY("待申请"), WAIT_AUDIT("待审核"), AUDIT_PASS("审核通过"), AUDIT_FAIL("审核不通过")} status 产品状态
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {String} serveRate 服务费比率
     * @apiSuccess {String=SHOP_PICKUP("到店自取"), SHIPPING("物流"), SHOP_PICKUP_AND_SHIPPING("物流及到店自取")} shippingType 支持的物流类型
     * @apiSuccess {String} marketId 分销产品唯一的识别码
     * @apiSuccess {String} marketProductType 分销市场属性
     * @apiSuccess {String} extSourceId 供应商ID
     * @apiSuccess {String} marketPlatformType 平台属性
     * @apiSuccess {String} merchantName 商家名称
     * @apiSuccess {String} resellFee 分销佣金
     * @apiSuccess {String} shareFee 分享返利
     * @apiSuccess {Date} dateEnabled 有效期开始时间
     * @apiSuccess {Date} dateDisabled 有效期结束时间
     * @apiSuccess {String} merchantStoreIds 产品适用门店ids
     * @apiSuccess {String} merchantStoreNames 产品适用门店名称
     * @apiSuccess {Long} categoryName 产品品类名称
     * @apiSuccess {String} introduce 产品介绍
     * @apiSuccess {String} manual 产品详情
     * @apiSuccess {List} logoUrls LOGO图集
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "id": 71,
     *      "dateCreated": "2016-06-01 14:13:43",
     *      "lastUpdated": "2016-07-22 10:49:28",
     *      "type": "GOODS",
     *      "name": "宇宙",
     *      "basePrice": 110,
     *      "sellPrice": 100,
     *      "quantity": 998,
     *      "carriage": 0,
     *      "refundable": false,
     *      "sellnow": true,
     *      "barcode": 234234234,
     *      "dateSelling": "2016-06-01 14:13:43",
     *      "limitCount": 0,
     *      "logoUrl": "/20160601/201606011413084VOvLKgN.jpg",
     *      "note": "全宇宙最漂亮的",
     *      "status": "SELLING",
     *      "mallId": 1,
     *      "merchantId": 1,
     *      "serveRate": "2.4",
     *      "shippingType": "SHIPPING",
     *      "resellFee": 5,
     *      "shareFee": 2,
     *      "marketId": 232,
     *      "marketProductType": "TARGET",
     *      "marketPlatformType": "OUT_PLATFORM",
     *      "extSourceId": "29",
     *      "dateEnabled": "2016-06-01 14:13:43",
     *      "dateDisabled": "2016-06-01 14:13:43",
     *      "introduce": "详情",
     *      "manual": "图文详情",
     *      "merchantStoreIds": [2,3,4],
     *      "categoryName": "美食--川湘菜:客家菜",
     *      "logoUrls" : ["3432.jpg","34242234.jpg"]
     * }
     * }
     */
    @RequestMapping(value = Routes.MALL_PRODUCT_INFO, method = RequestMethod.GET)
    public JsonResult info(HttpServletRequest request, ProductDto productDto) {
        RestDoing doing = jsonResult -> {
            if(productDto.getId()==null){
                jsonResult.remind("产品id 不能为空",log);
                return;
            }
            Product product = mallProductRepository.findOne(productDto.getId());
            if(product==null) {
                jsonResult.remind("产品记录不存在",log);
                return;
            }
            RBeanUtils.copyProperties(product, productDto);
            Double basePrice = null == product.getBasePrice() ? null : Double.valueOf(product.getBasePrice().toString());
            //原价
            productDto.setBasePrice(basePrice);
            //出售价
            productDto.setSellPrice(Double.valueOf(product.getSellPrice().toString()));
            //产品状态
            productDto.setStatus(String.valueOf(product.getStatus()));
            //产品类型
            productDto.setType(String.valueOf(product.getType()));
            //支持的物流类型
            if (product.getShippingType() != null) {
                productDto.setShippingType(String.valueOf(product.getShippingType()));
            }
            // 产品适用门店
            productDto.setMerchantStoreNames(merchantProductSrvImpl.getProductStoreNames(product.getProductMerchantStoreType(),product.getId(),product.getMerchantId()));
            // 产品品类
            List<ProductCategories> productCategoriesList = merchantProductCategoriesRepository.findByProductId(product.getId());
            if(productCategoriesList!=null && productCategoriesList.size()>0) {
                Category category = categoryRepository.findOne(productCategoriesList.get(0).getCategoryId());
                StringBuilder str = merchantProductSrvImpl.parentName(category.getParentId());
                for(ProductCategories categories: productCategoriesList) {
                    str.append(categoryRepository.findOne(categories.getCategoryId()).getName()).append(":");
                }
                productDto.setCategoryName(str.substring(0,str.length()-1));
            }
            //LOGO图集
            productDto.setLogoUrls(new ArrayList<>());
            if (product.getLogoUrls() != null) {
                productDto.setLogoUrls(objectMapper.readValue(product.getLogoUrls(), new TypeReference<List<String>>() { }));
            }
            //分享返利
            productDto.setShareFee(Double.valueOf(String.valueOf(product.getShareFee())));
            //分销佣金
            productDto.setResellFee(Double.valueOf(String.valueOf(product.getResellFee())));
            //分销市场属性
            if (product.getProductMerchantStoreType() != null) {
                productDto.setProductMerchantStoreType(String.valueOf(product.getProductMerchantStoreType()));
            }
            ProductDetail productDetail = merchantProductDetailRepository.findByProductId(product.getId());
            if (productDetail != null) {
                //产品介绍
                productDto.setIntroduce(productDetail.getIntroduce());
                //产品详情
                productDto.setManual(productDetail.getManual());
            }

            ProductQuantity pqs = productQuantityRepository.findById(product.getProductQuantityId());

            if( pqs != null ){
                long fronzen = pqs.getFrozenQuantity() == null ? 0 : pqs.getFrozenQuantity();
                long quantity = pqs.getQuantity() == null ? 0 : pqs.getQuantity();
                productDto.setQuantity(quantity - (fronzen > 0 ? fronzen : 0) );
            }

            jsonResult.data = productDto;
        };
        return doing.go(request, log);
    }

    /**
     * @api {put}/mall/product/update 产品管理 产品下架原因
     * @apiGroup M端 product
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id <code>必须参数</code> 产品ID
     * @apiParam {String} productUnderReason <code>必须参数</code> 产品下架原因
     *
     * @apiSuccess {String} succcess Y表示成功
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data":{
     *      "success": "Y"
     *   }
     * }
     */
    @RequestMapping(value = Routes.MALL_PRODUCT_UPDATE, method = RequestMethod.PUT)
    public JsonResult update(HttpServletRequest request, @RequestBody ProductDto productDto) {
        RestDoing doing = jsonResult -> {
            if (productDto.getId() == null) {
                jsonResult.remind("产品id 不能为空",log);
                return;
            }
            if (StringUtils.isBlank(productDto.getProductUnderReason())) {
                jsonResult.remind("产品下架原因 不能为空",log);
                return;
            }
            Product product = mallProductRepository.findOne(productDto.getId());
            if(product==null) {
                jsonResult.remind("产品记录不存在",log);
                return;
            }
            if(ProductStatus.ILLEGAL.equals(product.getStatus())) {
                jsonResult.remind("产品已下架",log);
                return;
            }
            product.setStatus(ProductStatus.ILLEGAL);
            mallProductRepository.save(product);
            MallProductReason mallProductReason = new MallProductReason();
            mallProductReason.setProductId(product.getId());
            mallProductReason.setReason(productDto.getProductUnderReason());
            mallProductReasonRepository.save(mallProductReason);
            List<Product> productList = mallProductRepository.findByMarketId(product.getId());
            if(productList!=null && productList.size()>0) {
                merchantProductSrvImpl.updateProductStatus(productList, ProductStatus.ILLEGAL);
            }
            String ret = "{\"success\":\"Y\"}";
            jsonResult.data = JSONObject.fromObject(ret);
        };
        return doing.go(request, log);
    }

    /**
     * 功能：判断字符串是否为日期格式
     * @param strDate
     * @return
     */
    private boolean isDate(String strDate) {
        Pattern pattern = Pattern
                .compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
        Matcher m = pattern.matcher(strDate);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }
}